package edu.zzuli.common.security;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.acegisecurity.ConfigAttributeEditor;
import org.springframework.jdbc.core.JdbcTemplate;

public class DBUrlSourceManager {
	
	private JdbcTemplate acegiJdbcTemplate;

	private String urlFindSql;

	private Map urlMap;

	private String COL_URL = "URL";

	private String COL_JS = "JS";

	public void setAcegiJdbcTemplate(JdbcTemplate acegiJdbcTemplate) {
		this.acegiJdbcTemplate = acegiJdbcTemplate;
	}

	public void setUrlFindSql(String urlFindSql) {
		this.urlFindSql = urlFindSql;
	}

	public void setCOL_URL(String COL_URL) {
		this.COL_URL = COL_URL;
	}

	public void setCOL_JS(String COL_JS) {
		this.COL_JS = COL_JS;
	}

	public Map getUrlMap() {
		if (this.urlMap == null) {
			this.sortMap();
			convertToConfigAttributeDefinition();
			System.out.println("[ConfigAttributeDefinition Map]"+this.urlMap.toString());
		}
		return this.urlMap;
	}

	public void clearUrlMap() {
		this.urlMap = null;
	}

	private void sortMap() {
		this.urlMap = new Hashtable();
		List listUrl = this.acegiJdbcTemplate.queryForList(this.urlFindSql);
		if (listUrl == null)
			return;
		for (int i = 0; i < listUrl.size(); i++) {
			Map qxMap = (Map) listUrl.get(i);
			String strUrl = this.convertUrl((String) qxMap.get(this.COL_URL));
			String strJs = qxMap.get(this.COL_JS).toString();
			String strJs_Former = (String) this.urlMap.get(strUrl);
			if (strJs_Former != null) {
				strJs = strJs_Former + "," + strJs;
			}
			this.urlMap.put(strUrl, strJs);

//			System.out.println(qxMap.toString());
		}
	}
	private void convertToConfigAttributeDefinition () {
		Iterator it = this.urlMap.keySet().iterator();
		while (it.hasNext()) {
			String strUrl = (String)it.next();
			String authStr = (String)this.urlMap.get(strUrl);
			ConfigAttributeEditor configAttrEditor = new ConfigAttributeEditor();
			configAttrEditor.setAsText(authStr);
			this.urlMap.put(strUrl, configAttrEditor.getValue());
		}
	}

	public String convertUrl(String str) {
		if (str.indexOf("/") != -1) {
			int index = str.lastIndexOf("/") + 1;
			str = str.substring(0, index);
		}
		str = "\\A" + str + ".*\\Z";
		return str;
	}
}
